<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('candidate.fields.studentName')" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.studentName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.jobCode')" prop="jobCode">
        <el-input
          v-model="queryParams.jobCode"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.jobCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.researchDept')" prop="researchDept">
        <el-input
          v-model="queryParams.researchDept"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.researchDept')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.major')" prop="major">
        <el-input
          v-model="queryParams.major"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.major')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.accountType')" prop="accountType">
        <el-select
          v-model="queryParams.accountType"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.accountType')"
          clearable
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option label="中国科大学生" value="中国科大学生" />
          <el-option label="联合培养学生" value="联合培养学生" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('candidate.fields.studentLevel')" prop="studentLevel">
        <el-select
          v-model="queryParams.studentLevel"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.studentLevel')"
          clearable
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option label="硕士研究生" value="硕士研究生" />
          <el-option label="博士研究生" value="博士研究生" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('candidate.fields.awardId')" prop="awardsName">
        <el-input
          v-model="queryParams.awardsName"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.awardId')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.templateId')" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.templateId')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.year')" prop="year">
        <el-input
          v-model="queryParams.year"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.year')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.processStatus')" prop="processStatus">
        <el-select
          v-model="queryParams.processStatus"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.processStatus')"
          clearable
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option :label="t('candidate.index.processStatus.underway')" :value="0" />
          <el-option :label="t('candidate.index.processStatus.passed')" :value="1" />
          <el-option :label="t('candidate.index.processStatus.failed')" :value="2" />
          <el-option :label="t('candidate.index.processStatus.draft')" :value="3" />
          <el-option :label="t('candidate.index.processStatus.cancel')" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('candidate.fields.result')" prop="result">
        <el-select
          v-model="queryParams.result"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.result')"
          clearable
          @change="handleQuery"
          class="!w-240px"
        >
          <el-option :label="t('candidate.index.result.unset')" :value="0" />
          <el-option :label="t('candidate.index.result.passed')" :value="1" />
          <el-option :label="t('candidate.index.result.failed')" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iCandidate-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('candidate.fields.awardId')"
        field="awardsName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.templateId')"
        field="templateName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.year')"
        field="year"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.jobCode')"
        field="jobCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.studentName')"
        field="studentName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.gender')"
        field="gender"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.researchDept')"
        field="researchDept"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.mentorName')"
        field="mentorName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <div class="flex items-center justify-center gap-[5px]">
            <span>{{ scope.row.mentorName }}</span>
            <el-tooltip
              v-if="scope.row.isInitialJudge || scope.row.isFinalJudge"
              effect="dark"
              placement="top"
            >
              <template #content>
                <div v-if="scope.row.isInitialJudge && scope.row.isFinalJudge">
                  {{ t('instance.index.initialAndFinal') }}
                </div>
                <div v-if="scope.row.isInitialJudge">
                  {{ t('instance.index.initialJudge') }}
                </div>
                <div v-if="scope.row.isFinalJudge">
                  {{ t('instance.index.finalJudge') }}
                </div>
              </template>
              <el-icon color="#ff0000" style="cursor: pointer"><WarningFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.secondaryMentorName')"
        field="secondaryMentorName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.major')"
        field="major"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.awardMajor')"
        field="awardMajor"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.studentLevel')"
        field="studentLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.awardLevel')"
        field="awardLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.accountType')"
        field="accountType"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.applyDetail')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleApplyDetail(scope.row)">
            {{ t('action.detail') }}
          </el-button>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.studentDetail')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleStudentDetail(scope.row)">
            {{ t('action.detail') }}
          </el-button>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.attachment')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.attachment && scope.row.attachment !== '[]'"
            link
            type="primary"
            @click="handlePreview(scope.row)"
          >
            {{ t('fileObjectDownload.buttonName') }}
          </el-button>
          <span v-else>{{ t('fileObjectDownload.noFile') }}</span>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.processDetail')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.processInstanceId"
            link
            type="primary"
            @click="openProcessInstance(scope.row)"
          >
            {{ t('action.detail') }}
          </el-button>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.processStatus')"
        field="processStatus"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <div v-if="scope.row.processStatus === 0"
            >{{ t('candidate.index.processStatus.underway') }}
          </div>
          <div v-if="scope.row.processStatus === 1"
            >{{ t('candidate.index.processStatus.passed') }}
          </div>
          <div v-if="scope.row.processStatus === 2"
            >{{ t('candidate.index.processStatus.failed') }}
          </div>
          <div v-if="scope.row.processStatus === 3"
            >{{ t('candidate.index.processStatus.draft') }}
          </div>
          <div
            v-if="scope.row.processStatus === 4"
            class="flex justify-center items-center gap-[5px]"
          >
            {{ t('candidate.index.processStatus.cancel') }}
            <el-tooltip effect="dark" placement="top">
              <template #content>
                {{ t('candidate.fields.cancelReason') }}: {{ scope.row.cancelReason }}
              </template>
              <el-icon :size="16" color="#ff0000"><WarnTriangleFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </vxe-column>
      <!--      <vxe-column-->
      <!--        :title="t('candidate.fields.qualityStatus')"-->
      <!--        field="qualityStatus"-->
      <!--        align="center"-->
      <!--        show-header-overflow-->
      <!--        show-overflow-->
      <!--        min-width="100"-->
      <!--      >-->
      <!--        <template #default="scope">-->
      <!--          <div v-if="scope.row.qualityStatus === 0"-->
      <!--            >{{ t('candidate.index.qualityStatus.unset') }}-->
      <!--          </div>-->
      <!--          <div v-if="scope.row.qualityStatus === 1"-->
      <!--            >{{ t('candidate.index.qualityStatus.passed') }}-->
      <!--          </div>-->
      <!--          <div v-if="scope.row.qualityStatus === 2"-->
      <!--            >{{ t('candidate.index.qualityStatus.failed') }}-->
      <!--          </div>-->
      <!--          <div v-if="scope.row.qualityStatus === 3"-->
      <!--            >{{ t('candidate.index.qualityStatus.notRequired') }}-->
      <!--          </div>-->
      <!--        </template>-->
      <!--      </vxe-column>-->
      <vxe-column
        :title="t('candidate.fields.result')"
        field="result"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <div v-if="scope.row.result === 0">{{ t('candidate.index.result.unset') }}</div>
          <div v-if="scope.row.result === 1">{{ t('candidate.index.result.passed') }}</div>
          <div v-if="scope.row.result === 2">{{ t('candidate.index.result.failed') }}</div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="140"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleEditLevel(scope.row)">
            {{ t('candidate.index.operate.editAwardLevel') }}
          </el-button>
          <el-button link type="primary" @click="handleEditMajor(scope.row)">
            {{ t('candidate.index.operate.editAwardMajor') }}
          </el-button>
          <el-button
            v-if="scope.row.processStatus === 1"
            link
            type="primary"
            @click="handleCancelQuality(scope.row)"
          >
            {{ t('candidate.index.operate.editCancel') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CandidateForm ref="formRef" @success="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="候选人"
    upload-url="/awards/candidate/import"
    template-url="/awards/candidate/get-import-template"
    @success="getList"
  />

  <!-- 申请详情 -->
  <CandidateApplicationInformation ref="awardStudentApplyInfoRef" />
  <!-- 流程详情 -->
  <ProcessInstancePopupView ref="processInstancePopupView" />

  <EditAwardLevelForm ref="editAwardLevelFormRef" @success="getList" />
  <EditAwardMajorForm ref="editAwardMajorFormRef" @success="getList" />

  <UstcStudentView ref="ustcStudentViewRef" @refresh="getList" />
  <ImrStudentView ref="imrStudentViewRef" @refresh="getList" />

  <!-- 文件预览弹窗 -->
  <FilePreviewDialog ref="filePreviewRef" type="pdf" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { CandidateApi, CandidateVO } from '@/api/awards/candidate'
import CandidateForm from './CandidateForm.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import ProcessInstancePopupView from '@/views/bpm/processInstance/detail/ProcessInstancePopupView.vue'
import EditAwardLevelForm from './components/EditAwardLevelForm.vue'
import EditAwardMajorForm from './components/EditAwardMajorForm.vue'
import CandidateApplicationInformation from '@/views/awards/components/CandidateApplicationInformation.vue'
import UstcStudentView from '@/views/core/ustcstudent/components/UstcStudentView.vue'
import ImrStudentView from '@/views/core/imrstudent/components/ImrStudentView.vue'
import FilePreviewDialog from '@/components/FilePreview/FilePreviewDialog.vue'
import { WarningFilled, WarnTriangleFilled } from '@element-plus/icons-vue'

/** 候选人 列表 */
defineOptions({ name: 'Candidate' })

const route = useRoute()
const router = useRouter() // 路由对象
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<CandidateVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  processInstanceId: undefined,
  accountId: undefined,
  year: undefined,
  awardId: undefined,
  awardsName: undefined,
  studentLevel: undefined,
  templateId: undefined,
  templateName: undefined,
  awardLevel: undefined,
  jobCode: undefined,
  major: undefined,
  studentName: undefined,
  awardMajor: undefined,
  gender: undefined,
  accountType: undefined,
  mentorId: undefined,
  mentorName: undefined,
  mentorCode: undefined,
  researchDeptId: undefined,
  researchDept: undefined,
  processStatus: undefined,
  qualityStatus: undefined,
  applySource: undefined,
  attachment: undefined,
  result: undefined,
  historyAwardsJson: undefined,
  selfIntroduction: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  queryParams.awardId = awardsId.value
  try {
    const data = await CandidateApi.getCandidatePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof CandidateForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CandidateApi.deleteCandidate(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CandidateApi.exportCandidate(queryParams)
    download.excel(data, '候选人.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const processInstancePopupView = ref<InstanceType<typeof ProcessInstancePopupView>>()
const openProcessInstance = (row: CandidateVO) => {
  processInstancePopupView.value?.show(row.processInstanceId)
}

const awardStudentApplyInfoRef = ref<InstanceType<typeof CandidateApplicationInformation>>()
const handleApplyDetail = (row: CandidateVO) => {
  awardStudentApplyInfoRef.value?.open(row.id)
}

const filePreviewRef = ref<InstanceType<typeof FilePreviewDialog>>()
const handlePreview = (row: CandidateVO) => {
  filePreviewRef.value?.open(row.attachment)
}

const ustcStudentViewRef = ref<InstanceType<typeof UstcStudentView>>()
const imrStudentViewRef = ref<InstanceType<typeof ImrStudentView>>()

const handleStudentDetail = (row: CandidateVO) => {
  if (!row.id) {
    return
  }
  if (row.accountType === '中国科大学生') {
    ustcStudentViewRef.value?.open(row.accountId)
  } else if (row.accountType === '联合培养学生') {
    imrStudentViewRef.value?.open(row.studentId, 'view')
  }
}

const editAwardLevelFormRef = ref<InstanceType<typeof EditAwardLevelForm>>()
const handleEditLevel = (row: CandidateVO) => {
  editAwardLevelFormRef.value?.open(row.id)
}

const editAwardMajorFormRef = ref<InstanceType<typeof EditAwardMajorForm>>()
const handleEditMajor = (row: CandidateVO) => {
  editAwardMajorFormRef.value?.open(row.id)
}

const handleCancelQuality = async (row: CandidateVO) => {
  try {
    const { value } = await ElMessageBox.prompt(
      t('candidate.index.operate.cancelTip'),
      t('common.confirmTitle')
    )
    if (!value) {
      message.error(t('common.inputTextPlaceholder') + t('candidate.fields.cancelReason'))
      return
    }

    try {
      await ElMessageBox.confirm(
        t('candidate.index.operate.cancelConfirm', { name: row.studentName }),
        t('common.confirmTitle'),
        { type: 'warning' } as any
      )
    } catch {
      return
    }

    try {
      loading.value = true
      await CandidateApi.cancelCandidateByAdmin({
        id: row.id,
        cancelReason: value
      })
      message.success(t('candidate.index.operate.cancelSuccess'))
      await getList()
    } finally {
      loading.value = false
    }
  } catch {
    return
  }
}

const awardsId = ref('')
/** 初始化 **/
onMounted(() => {
  if (!route.params.instanceId) {
    router.push('/awards/instance')
    return
  }
  awardsId.value = route.params.instanceId as string

  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}
</style>
